package com.corpgovernment.supplier.controller;

import com.corpgovernment.api.supplier.soa.constant.ProductTypeEnum;
import com.corpgovernment.api.supplier.soa.request.QuerySupplierCodeIsExistRequest;
import com.corpgovernment.api.supplier.soa.request.GetSupplierInfoRequest;
import com.corpgovernment.api.supplier.soa.request.QuerySupplierListByNameOrCodeRequest;
import com.corpgovernment.api.supplier.soa.response.MbSupplierInfoResponse;
import com.corpgovernment.api.supplier.soa.response.MbSupplierListResponse;
import com.corpgovernment.api.supplier.soa.response.GetSupplierInfoResponse;
import com.corpgovernment.api.supplier.vo.MbSupplierInfoVo;
import com.corpgovernment.common.base.Id;
import com.corpgovernment.common.base.JSONResult;
import com.corpgovernment.common.common.CorpBusinessException;
import com.corpgovernment.common.operatelog.OperateLog;
import com.corpgovernment.common.operatelog.constant.OperateLogContant;
import com.corpgovernment.organization.constant.OrganizationResponseCodeEnum;
import com.corpgovernment.organization.vo.PageVo;
import com.corpgovernment.supplier.entity.db.MbSupplierInfo;
import com.corpgovernment.supplier.mapper.MbSupplierInfoMapper;
import com.corpgovernment.supplier.service.MbSupplierInfoService;
import com.corpgovernment.supplier.vo.QuerySupplierListRequest;
import com.corpgovernment.supplier.vo.SupplierDataModelMapper;
import com.corpgovernment.supplier.vo.SupplierInfoRequest;
import com.corpgovernment.supplier.vo.suppliercompany.SupportSupplierInfoVo;
import com.ctrip.corp.obt.generic.utils.CollectionUtils;
import com.ctrip.corp.obt.generic.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("mbSupplierInfo")
@Slf4j
public class MbSupplierInfoController {

    @Autowired
    private MbSupplierInfoService supplierInfoService;
    @Autowired
    private SupplierDataModelMapper supplierDataModelMapper;
    @Autowired
    private MbSupplierInfoMapper supplierInfoMapper;

    @PostMapping("/listAll")
    public JSONResult<List<MbSupplierInfoResponse>> listAll() {
        return JSONResult.success(supplierInfoService.listUnFreeze().stream().map(msi -> {
            MbSupplierInfoResponse msir = new MbSupplierInfoResponse();
            msir.setSupplierName(msi.getSupplierName());
            msir.setSupplierCode(msi.getSupplierCode());
            msir.setContactEmail(msi.getContactEmail());
            return msir;
        }).collect(Collectors.toList()));
    }

    @PostMapping("querySupplierCodeIsExist")
    public JSONResult<?> querySupplierCodeIsExist(@RequestBody QuerySupplierCodeIsExistRequest request) {
        boolean exists = supplierInfoService.loadBySupplierCode(request.getNameOrCode()) != null;
        if (exists) {
            return JSONResult.errorMsg("服务商ID已存在，请重试！");
        }
        return JSONResult.ok();
    }

    /**
     * http://10.5.119.87:9526/project/494/interface/api/11556
     * 根据SupplierCode 和 SupplierName 模糊查询服务商列表
     * corpId 传入时，会过滤该公司下关联(除新建状态)的服务商
     */
    @PostMapping("querySupplierListByNameOrCode")
    public JSONResult<List<MbSupplierInfo>> querySupplierListByNameOrCode(@RequestBody QuerySupplierListByNameOrCodeRequest request) {
        return JSONResult.success(supplierInfoService.querySupplierListByNameOrCode(request.getNameOrCode(), request.getCorpId()));
    }

    /**
     * 冻结/解冻服务商
     * 如该公司下关联(除新建状态)的服务商，则无法冻结
     * http://10.5.119.87:9526/project/494/interface/api/11756
     */
    @PostMapping("/frozenOrUnFrozen")
    public JSONResult<Boolean> frozenOrUnFrozen(@RequestBody @Validated(SupplierInfoRequest.Frozen.class) SupplierInfoRequest req) {
        if (req.getFrozen()) {
            supplierInfoService.froze(req.getId());
        } else {
            supplierInfoService.unFroze(req.getId());
        }
        return JSONResult.ok();
    }

    /**
     * 分页查询
     * http://10.5.119.87:9526/project/494/interface/api/11484
     */
    @PostMapping("/getSupplierList")
    public JSONResult<PageVo> getSupplierList(@RequestBody @Valid QuerySupplierListRequest request) {
        return JSONResult.success(supplierInfoService.getSupplierList(request));
    }

    /**
     * 删除服务商信息。会清空
     * at_user_login
     * mb_supplier_info
     * mb_supplier_extend_info
     * http://10.5.119.87:9526/project/494/interface/api/11752
     */
    @PostMapping("/deleteSupplier")
    @OperateLog(OperateLogContant.DELETESUPPLIERINFO)
    public JSONResult<Boolean> deleteSupplier(@RequestBody @Valid Id<Long> req) {
        supplierInfoService.delete(req.getId());
        return JSONResult.ok();
    }

    /**
     * http://10.5.119.87:9526/project/494/interface/api/11780
     */
    @PostMapping("/getSupplierInfo")
    public JSONResult<MbSupplierInfoVo> getSupplierInfo(@RequestBody @Valid Id<Long> req) {
        List<MbSupplierInfoVo> results = supplierInfoService.loadSupplierInfo(Collections.singletonList(req.getId()), null);
        if (CollectionUtils.isEmpty(results)) {
            return JSONResult.ok();
        }
        return JSONResult.success(results.get(0));
    }

    /**
     * 更新时会忽略 supplierCode 和管理员信息
     * http://10.5.119.87:9526/project/494/interface/api/11784
     */
    @PostMapping("/insertOrUpdateSupplierInfo")
    @OperateLog(OperateLogContant.INSERTORUPDATESUPPLIERINFO)
    public JSONResult<?> insertOrUpdateSupplierInfo(@RequestBody MbSupplierInfoVo si) {
        supplierInfoService.validateParams(si);
        MbSupplierInfoService.SupplierInfo sp = supplierDataModelMapper.map2Entity(si);
        if (si.getId() == null) {
            supplierInfoService.insert(sp);
        } else {
            supplierInfoService.update(sp);
        }
        return JSONResult.ok();
    }

    @PostMapping("/getSupplierInfoBySupplierCode")
    public JSONResult<MbSupplierInfoVo> getSupplierInfoBy(@RequestParam("supplierCode") String supplierCode) {
        List<MbSupplierInfoVo> results = supplierInfoService.loadSupplierInfo(null, Collections.singletonList(supplierCode));
        if (CollectionUtils.isEmpty(results)) {
            return JSONResult.ok();
        }
        return JSONResult.success(results.get(0));
    }

    /**
     * 获取服务商提供的产品列表
     * http://10.5.119.87:9526/project/494/interface/api/12156
     */
    @PostMapping("/getSupportProducts")
    public JSONResult<List<Map<String, String>>> getSupportProducts(@RequestBody SupplierInfoRequest req) {
        if (StringUtils.isBlank(req.getSupplierCode())) {
            throw new CorpBusinessException(OrganizationResponseCodeEnum.SUPPLIER_CODE_NULL);
        }
        MbSupplierInfo si = supplierInfoService.loadBySupplierCode(req.getSupplierCode());
        if (si == null) {
            return JSONResult.ok();
        }
        return JSONResult.success(ProductTypeEnum.getProductEnum(si.getSupportProduct()).stream()
                .distinct()
                .filter(pt -> !ProductTypeEnum.i18n_flight.equals(pt))
                .map(pt -> {
                    Map<String, String> map = new HashMap<>();
                    map.put("id", pt.name());
                    map.put("name", pt.getDesc());
                    return map;
                }).collect(Collectors.toList()));
    }

    @PostMapping("/listUnfreeze")
    public JSONResult<MbSupplierListResponse> listUnfreeze() {
        MbSupplierListResponse resp = new MbSupplierListResponse();
        List<MbSupplierInfoResponse> msir = supplierInfoService.listUnFreeze().stream().map(si -> {
            MbSupplierInfoResponse sir = new MbSupplierInfoResponse();
            sir.setSupplierCode(si.getSupplierCode());
            sir.setSupplierName(si.getSupplierName());
            return sir;
        }).collect(Collectors.toList());
        resp.setSupplier(msir);
        return JSONResult.success(resp);
    }

    /**
     * 获取PC首页联系服务商。加载出所有服务商
     * 不包括禁用，逻辑删除
     * P202001020119   http://tswork.flight.ctripcorp.com/home/FrameView?url=/Project/ProjDetail&projId=51604
     */
    @PostMapping("/listSupplier")
    public JSONResult<List<SupportSupplierInfoVo>> listSuppliers() {
        List<SupportSupplierInfoVo> collect = supplierInfoMapper.loadSupplierInfos().stream()
                .peek(ssiv -> {
                    String productStr = String.join(", ", ProductTypeEnum.getProductEnum(ssiv.getSupportProduct()).stream().map(ProductTypeEnum::getDesc)
                            .filter(e -> !ProductTypeEnum.other.getDesc().equals(e)).collect(Collectors.toSet()));
                    ssiv.setProduct(productStr);
                }).collect(Collectors.toList());

        return JSONResult.success(collect);
    }

    @RequestMapping("/getSupplierInfoBySupplier")
    public JSONResult<MbSupplierInfoVo> getSupplierInfoBySupplier(@RequestParam("supplierCode") String supplierCode) {
        return JSONResult.success(supplierInfoService.get(supplierCode));
    }

    /**
     * 结算台获取供应商信息
     *
     * @param request
     * @return
     */
    @PostMapping("querySupplierInfo")
    public JSONResult<List<MbSupplierInfoVo>>
        querySupplierInfo(@RequestBody QuerySupplierListByNameOrCodeRequest request) {
        return JSONResult.success(supplierInfoService.querySupplierInfo(request.getNameOrCode(), null));
    }


    /**
     * openapi对外暴露查询供应商信息接口
     *
     * @param request
     * @return
     */
    @PostMapping("soaGetSupplierInfo")
    public JSONResult<GetSupplierInfoResponse> soaGetSupplierInfo(@RequestBody @Valid GetSupplierInfoRequest request) {
        return JSONResult.success(supplierInfoService.soaGetSupplierInfo(request.getSupplierCode()));
    }
}
